import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class SplashImage extends Canvas
{
	private Image icon;
	private String title;
	private SplashIIMIDlet mgr;
	private int status;
	private int max;
	private boolean done = false;
	private SplashImageThread sit;
	
	public SplashImage(SplashIIMIDlet mm, String title, String url, int max)
	{
		this.title = title;
		this.mgr = mm;
		this.max = max;
		try
		{
			this.icon = Image.createImage("/send.png");
		}
		catch(Exception e)
		{
			System.out.println("Ne morem naloziti slike.");
		}
		
		sit = new SplashImageThread(url, this);
	}
	
	public void done()
	{
		this.done = true;
	}
	
	public void connect()
	{
		this.sit.connect();
		
		/* timeout count */
		long timeout = System.currentTimeMillis() + (30 * 1000);
		
		while(System.currentTimeMillis() < timeout)
		{
			if(this.done)
				break;
			
			try
			{
				Thread.sleep(10);
			}
			catch(Exception e){}
		}
		
		if(this.done)
			repaint();
		else
			mgr.setScreen(new SplashAlert(mgr, SplashAlert.ERROR, "Nalaganje ni uspelo"),
							FormConstants.ALERT);
	}
	
	public boolean error()
	{
		return sit.error();
	}
	
	public void cancelConnection()
	{
		this.sit = null;
	}
	
	protected void keyReleased(int keyCode)
	{
		/* Cancel */
		mgr.itemSelected(0);
	}
	
	public void setTitle(String title)
	{
		this.title = title;
		repaint();
	}
	
	public void setIcon(Image img)
	{
		this.icon = img;
		repaint();
	}
	
	public void paint(Graphics g)
	{
		int hcenter = getWidth() / 2;
		int vcenter = getHeight() / 2;
		
		if(done && (this.icon = sit.getScreen()) != null)
		{

			if(getHeight() > getWidth())
				icon = Image.createImage(icon, 0, 0, icon.getWidth(), icon.getHeight(), Sprite.TRANS_ROT270);
				
			g.drawImage(icon, 0, 0, Graphics.TOP | Graphics.LEFT);
			return;
		}
		
		g.setColor(mgr.getDefaultBGColor());
		g.fillRect(0,0, getWidth(), getHeight());
		
		g.setColor(0x00FFFFFF - g.getColor());
		
		g.drawImage(icon, hcenter, vcenter, Graphics.VCENTER | Graphics.HCENTER);
		
		g.drawString(title, hcenter, getHeight() - 20, Graphics.BASELINE | Graphics.HCENTER);
		g.drawString("Pritisni katerokoli tipko za preklic", hcenter, 20, Graphics.BASELINE | Graphics.HCENTER);
	}
}
